const app = getApp()

Page({
  data: {
    addressList: [],
    selectedAddressId: null
  },
  
  onLoad(options) {
    this.loadAddressList()
    // 如果是选择地址模式，记录选择状态
    if (options.selectMode === 'true') {
      this.setData({ selectMode: true })
    }
  },
  
  loadAddressList() {
    // 模拟加载地址数据
    const mockAddresses = [
      {
        id: 1,
        name: '张三',
        phone: '13800138000',
        province: '广东省',
        city: '深圳市',
        district: '南山区',
        detail: '科技园南区',
        isDefault: true
      },
      {
        id: 2,
        name: '李四',
        phone: '13900139000',
        province: '北京市',
        city: '北京市',
        district: '朝阳区',
        detail: '国贸大厦A座',
        isDefault: false
      }
    ]
    
    this.setData({ addressList: mockAddresses })
  },
  
  selectAddress(e) {
    const addressId = e.currentTarget.dataset.id
    if (this.data.selectMode) {
      // 选择地址模式，返回选择的地址
      const selectedAddress = this.data.addressList.find(addr => addr.id === addressId)
      if (selectedAddress) {
        const pages = getCurrentPages()
        const prevPage = pages[pages.length - 2]
        if (prevPage) {
          // 直接设置选择地址的数据到上一页
          prevPage.setData({
            selectedAddress: selectedAddress
          })
        }
        wx.navigateBack()
      }
    }
  },
  
  setDefaultAddress(e) {
    const addressId = e.currentTarget.dataset.id
    const addressList = this.data.addressList.map(addr => ({
      ...addr,
      isDefault: addr.id === addressId
    }))
    this.setData({ addressList })
    
    wx.showToast({
      title: '设置默认地址成功',
      icon: 'success'
    })
  },
  
  editAddress(e) {
    const addressId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/user/address-edit?id=${addressId || ''}`
    })
  },
  
  deleteAddress(e) {
    const addressId = e.currentTarget.dataset.id
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个地址吗？',
      success: (res) => {
        if (res.confirm) {
          const addressList = this.data.addressList.filter(addr => addr.id !== addressId)
          this.setData({ addressList })
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
        }
      }
    })
  },
  
  addNewAddress() {
    wx.navigateTo({
      url: '/pages/user/address-edit'
    })
  },
  
  onShow() {
    // 页面显示时重新加载地址列表
    this.loadAddressList()
  }
})